import React, { useState, useEffect, useRef, useMemo } from 'react';
import styles from './index.module.less';
import FormGroup, { FormListItem } from '@/components/form-group';
import ButtonFooter from '@/components/button-footer';
import ContentCard from '../matter-card';
import DocMatter from './matter';
import { GenerateUUID } from '@/utils';
import { DOCUMENT_TYPE_LIST, DOCUMENT_TYPE, OFFICIAL_APPLY_SCOPE_LIST, OFFICIAL_APPLY_SCOPE_MAP } from '@/pages/official-doc/constants';
import classnames from 'classnames';
import { MatterItem, DocDetail as DocDetailType, StandardItem } from '@/pages/official-doc/interface';
import { FormContentType } from '@/pages/official-doc/components/doc-content/interface.d';
import { DocDetail } from '@/services/official-doc';
// import { orgData } from '@/services/design';
import { IOrgTreeItem } from '@/components/ContractSelectModal';
import { useDispatch, useSelector } from 'react-redux';
import { Toast } from 'antd-mobile-v2';

export interface Props {
  [propsNames: string]: any;
}

const DocTotal: React.FC<Props> = (props) => {
  const { handlePublish, handleSave, loading } = props;
  const formRef: React.MutableRefObject<any> = useRef();
  const [formData, setFormData] = useState({ documentEnterType: 2 } as DocDetailType); // 真实提交的表单数据
  const [target, setTarget] = useState({} as MatterItem);
  const [showNextForm, setShowNextForm] = useState(false);
  const docId = useRef(props.match?.params?.id);
  const dispatch = useDispatch();
  const { orgTree, userInfo = {} } = useSelector((state: any) => ({
    orgTree: state.common.orgTree,
    userInfo: state.common.userInfo
  }));

  useEffect(() => {
    getBaseInfo();
    getDocDetail();
  }, []);

  const getDocDetail = async () => {
    if (!docId.current) return;
    const res = await DocDetail(docId.current);
    const data = res.data;
    const info: DocDetailType = {
      ...data,
      org: data?.orgId ? [{ id: data?.orgId, name: data?.orgName, userOrgType: 1 }] : [],
      sign: data?.signId ? [{ id: data?.signId, name: data?.signName, userOrgType: 2 }] : [],
      anchor: data?.anchorId ? [{ id: data?.anchorId, name: data?.anchorName, userOrgType: 2 }] : [],
      participantIds: data.participantInfoList?.map((item: any) => ({ id: item.userId, name: item.userName, userOrgType: 2 }))
    };
    if (info?.triScope) {
      info.triScopeInfo = info.triScope?.split(',')?.map((item: any) => {
        return {
          value: item,
          label: OFFICIAL_APPLY_SCOPE_MAP[item] ? OFFICIAL_APPLY_SCOPE_MAP[item]?.label : OFFICIAL_APPLY_SCOPE_MAP[item]
        };
      });
    }
    console.log('info----{}', info);
    formRef.current.setValues(info);
    setFormData(info);
    // 单独回填事项
    // setTarget(info.matterAddList);
  };

  const formatList = (list: IOrgTreeItem[]) => {
    if (!list) return undefined;
    return list.map((item: IOrgTreeItem) => ({
      id: item.key || item.id,
      name: item.title || item.name,
      userOrgType: item.type || item.userOrgType
    }));
  };

  const getBaseInfo = () => {
    dispatch({ type: 'common/getOrgTreeDataSaga' });
    dispatch({ type: 'common/getUserInfoSaga' });
  };

  const handlePublishDoc = async () => {
    const data = await formRef.current.getValues();
    console.log('data------------{}', data);

    // id: "AaKmeMmrvcfLc5F"
    // name: "李卫军"
    // userOrgType: 2
    const newFormData = {
      ...formData,
      ...data,
      documentType: data.documentType,
      orgId: data.org[0]?.key,
      orgName: data.org[0]?.title,
      signId: data.sign?.map((item: any) => item.key)?.join('，'),
      signName: data.sign?.map((item: any) => item.title)?.join('，'),
      anchorId: data.anchor[0]?.key,
      anchorName: data.anchor[0]?.title,
      ccUserList: formatList(data.ccUserList),
      participantIds: data.participantIds?.map((item: any) => item.key)
    };
    if (!newFormData.matterAddList?.[0]?.matterName) {
      // 没有事项时，不能发布（matterName-事项名是事项的必填字段）
      return Toast.fail('请添加事项');
    }
    setFormData(newFormData);
    handlePublish(newFormData);
  };

  const handleSaveDoc = async () => {
    console.log('handleSaveDoc enter');
    const data = await formRef.current.getValues();
    console.log('handleSaveDoc data', data);
    const newFormData = {
      ...formData,
      ...data,
      documentType: data.documentType,
      orgId: data.org[0]?.key,
      orgName: data.org[0]?.title,
      signId: data.sign?.map((item: any) => item.key)?.join('，'),
      signName: data.sign?.map((item: any) => item.title)?.join('，'),
      triScope: data?.triScopeInfo?.map((item: any) => item.value)?.join(','),
      anchorId: data.anchor[0]?.key,
      anchorName: data.anchor[0]?.title,
      ccUserList: formatList(data.ccUserList),
      participantIds: data.participantIds?.map((item: any) => item.key)
    };
    if (!newFormData.matterAddList?.[0]?.matterName) {
      return Toast.fail('请添加事项');
    }
    setFormData(newFormData);
    handleSave(newFormData);
  };

  const saveData = async () => {
    const data = await formRef.current.getData();
    const newFormData = {
      ...formData,
      ...data
    };
    setFormData(newFormData);
  };

  const goNextForm = () => {
    saveData();
    if (!formData.matterAddList?.length) {
      formData.matterAddList = [];
    }
    // 事项列表中先新增一项，事项页面点击确认添加后更新这一项的内容，事项页面点击返回时需要排除这一项
    formData.matterAddList.push({
      id: GenerateUUID(),
      standardAddList: [] as StandardItem[],
      sort: formData.matterAddList.length + 1
    } as MatterItem);
    setTarget(formData.matterAddList[formData.matterAddList.length - 1]);
    setShowNextForm(true);
  };

  // 点击确认或返回的回调
  const handleMatterChange = (data: MatterItem, type?: 'back') => {
    const matterAddList: MatterItem[] = [];
    formData.matterAddList?.forEach((item: MatterItem) => {
      if (item.id === data.id) {
        if (type === 'back') {
          if (!item.matterName) {
            // 不存在事项名称，说明是新添加的数据，不存入数组（这种判断是否为新添加数据的方式有点坑）
            return;
          }
          return matterAddList.push(item);
        }
        return matterAddList.push({ ...item, ...data });
      }
      return matterAddList.push(item);
    });
    setFormData({ ...formData, matterAddList });
    setShowNextForm(false);
  };

  const handleMatterDelete = (id: string) => {
    const matterAddList = formData.matterAddList?.filter((item: MatterItem) => {
      if (id === item.id) {
        return false;
      }
      return true;
    });
    setFormData({ ...formData, matterAddList });
  };

  const handleMatterClick = (data: any) => {
    let activeTarget;
    formData.matterAddList?.forEach((item: MatterItem) => {
      if (item.id === data.id) {
        activeTarget = item;
      }
    });
    if (activeTarget !== undefined) {
      setTarget(activeTarget);
      setShowNextForm(true);
    }
  };

  const getList = ({ orgTreeData, ccUserList, org, sign, anchor, participantIds, triScopeInfo }) => {
    console.log('triScopeInfo------{}', triScopeInfo);
    // console.log('userInfo', userInfo);
    // console.log('docId', docId);

    const formList: FormListItem[] = [
      {
        valueKey: 'org', label: '部门', type: 'treeSelecter',
        cellProps: {
          extra: '请选择',
          receiveData: org?.length ? org : [{ id: userInfo.user?.orgId, name: userInfo.user?.orgName, userOrgType: 1 }],
          type: 'dept',
          mode: 'single',
          orgData: orgTreeData,
          onChange: (value: any) => {
            if (!value?.length) return;
            formRef.current.setValues({
              documentName: `${value[0].title.replace(/\s/g, '')}党政联席会会议纪要`
            });
          }
        },
        options: { rules: [{ required: true, message: '请选择部门' }] }
      }, {
        valueKey: 'documentType', label: '公文类型', type: 'radioSelect',
        pickerOptions: DOCUMENT_TYPE_LIST,
        options: {
          rules: [{ required: true, message: '请选择公文类型' }],
          initialValue: DOCUMENT_TYPE.MEETING
        }
      }, {
        valueKey: 'documentName', label: '公文名称', type: 'input',
        options: { rules: [{ required: true, message: '请输入公文名称' }] },
        cellProps: { maxLength: 64 }
      }, {
        valueKey: 'documentCode', label: '公文号', type: 'input',
        options: { rules: [{ required: true, message: '请输入公文号' }, { whitespace: true, message: '公文号不能为空' }] },
        cellProps: { maxLength: 64 }
      }, {
        valueKey: 'sign', label: '签发人', type: 'treeSelecter',
        options: { rules: [{ required: false, message: '请选择签发人' }] },
        cellProps: {
          extra: '请选择',
          receiveData: sign,
          type: 'person',
          mode: 'multiple',
          orgData: orgTreeData
        }
        // options: { rules: [{ required: true, message: '请选择签发人' }] }
      }, {
        valueKey: 'meetingDate', label: '会议日期', type: 'datePicker',
        options: { rules: [{ required: true, message: '请选择会议日期' }] },
        cellProps: { extra: '请选择', backMode: 'time' }
      }, {
        valueKey: 'meetingPlace', label: '会议地点', type: 'input',
        options: { rules: [{ required: true, message: '请输入会议地点' }, { whitespace: true, message: '会议地点不能为空' }] },
        cellProps: { placeholder: '请输入', maxLength: 64 }
      }, {
        valueKey: 'anchor', label: '主持人', type: 'treeSelecter',
        options: { rules: [{ required: true, message: '请选择主持人' }] },
        cellProps: {
          extra: '请选择',
          receiveData: anchor,
          type: 'person',
          mode: 'single',
          orgData: orgTreeData
        }
      },
      {
        valueKey: 'participantIds', label: '参会人员', type: 'treeSelecter',
        options: { rules: [{ required: true, message: '请选择参会人员' }] },
        cellProps: {
          extra: '请选择',
          receiveData: participantIds,
          type: 'person',
          mode: 'multiple',
          orgData: orgTreeData
        }
      },
      {
        valueKey: 'remark', label: '备注', type: 'input',
        cellProps: { placeholder: '请输入（选填）', maxLength: 200 }
      },
      {
        valueKey: 'attachmentIds', label: '公文附件', type: 'filePicker',
        cellProps: {
          extra: '请选择',
          receiveData: formData.attachmentList,
          defaultFileType: ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'csv', 'pdf', 'jpe', 'jpg', 'jpeg', 'png', 'gif'],
          maxFileNumber: 10,
          defaultFileSize: 50
        },
        options: { rules: [{ required: true, message: '请上传公文附件' }] }
      },
      // receiveData: org?.length ? org : [{ id: userInfo.user?.orgId, name: userInfo.user?.orgName, userOrgType: 1 }],
      {
        valueKey: 'ccUserList', label: '抄送', type: 'treeSelecter',
        cellProps: {
          extra: '请选择',
          receiveData: ccUserList?.length ? ccUserList : [{ id: userInfo.user?.userId, name: userInfo.user?.userName, userOrgType: 2 }],
          // ccUserList?.length ?
          //   ccUserList : docId.current ?
          //     [] : [{ id: userInfo.user?.userId, name: userInfo.user?.userName, userOrgType: 2 }],
          type: 'all',
          mode: 'multiple',
          orgData: orgTreeData
        },
        options: { rules: [{ required: true, message: '请选择抄送' }] }
      },
      {
        valueKey: 'triScopeInfo', label: '适用范围', type: 'checkboxSelect',
        pickerOptions: OFFICIAL_APPLY_SCOPE_LIST,
        options: {
          rules: [{ required: true, message: '请选择适用范围' }]
        },
        cellProps: {
          className: 'triScopeInfo-item',
          onChange: (value: any) => {
            if (!value?.length) return;
          }
        }
      }
    ];
    return formList;
  };

  // 树形组件表单回填时，需要在这里注册
  const getListMemo = useMemo(() => getList({
    orgTreeData: orgTree,
    ccUserList: formData.ccUserList,
    org: formData.org,
    sign: formData.sign,
    anchor: formData.anchor,
    participantIds: formData.participantIds,
    triScopeInfo: formData.triScopeInfo
  }), [orgTree, formData.ccUserList, formData.org, formData.sign, formData.anchor,
    formData.participantIds, userInfo, formData.triScopeInfo]);

  const getButtonOptions = () => {
    if (formData?.status === 2) {
      return [
        {
          text: '发布',
          loading: loading.publish,
          onClick: handlePublishDoc
        }
      ];
    } else {
      return [
        // {
        //   text: (
        //     <span>
        //       <i className={classnames('icon', 'iconfont')}>&#xe6e0;</i>
        //       <span>删除</span>
        //     </span>
        //   ),
        //   className: 'noBorder',
        //   type: 'ghost',
        //   onClick: handlePublish
        // }, 
        // {
        //   text: '保存草稿',
        //   type: 'ghost',
        //   loading: loading.save,
        //   onClick: handleSaveDoc
        // }, 
        {
          text: '发布',
          loading: loading.publish,
          onClick: handlePublishDoc
        }
      ];
    }
  };

  return (
    <React.Fragment>
      <div className={classnames(styles.wrap, showNextForm ? styles.hide : '')}>
        <FormGroup
          routeBlock
          ref={formRef}
          formList={getListMemo}
          formData={formData}
        />
        {
          formData.matterAddList?.map((item: MatterItem, index: number) => (
            <ContentCard
              key={index}
              type={FormContentType.TOTAL}
              data={item}
              handleDelete={handleMatterDelete}
              handleClick={handleMatterClick}
            />
          ))
        }
        <div className={styles.addItem} onClick={goNextForm}>+ 添加事项明细</div>
        <ButtonFooter data={getButtonOptions()} />
      </div>
      {/* <div className={classnames(styles.wrap, !showNextForm ? styles.hide : '')}> */}
      {
        showNextForm && <DocMatter content={target} handleChange={handleMatterChange} />
      }
      {/* </div> */}
    </React.Fragment>
  );
};

export default DocTotal;